package com.wut.clock.auth;

import com.alibaba.fastjson.JSON;
import com.wut.clock.common.api.CommonResult;
import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: yuwei
 * @Date: 2022/5/30 10:46
 * @Description: 自定义shiro过滤器
 */

public class MyAuthFilter extends FormAuthenticationFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue){
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        return httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name());

    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
        String token = httpServletRequest.getHeader("Authorization");
        Subject subject = SecurityUtils.getSubject();
        if (StringUtils.isBlank(token) || !subject.isAuthenticated()) {
            HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
            httpResponse.setCharacterEncoding("UTF-8");
            CommonResult commonResult = CommonResult.unauthorized(null);
            String json = JSON.toJSONString(commonResult);
            httpResponse.getWriter().print(json);
            return false;
        }
        return true;
    }
}
